//
//  XMOauthTableViewController.swift
//  XMWeibo-Swift
//
//  Created by 育鑫 王 on 15/10/29.
//  Copyright © 2015年 育鑫 王. All rights reserved.
//

import UIKit
import SVProgressHUD

class XMOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
//        view.backgroundColor = UIColor.brownColor()

        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //加载网页
        let request = NSURLRequest(URL: XMNetworkTools.sharedInstance.oauthURL())
        webView.loadRequest(request)
    }
    
    ///关闭控制器
    func close () {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK : - 懒加载
    private lazy var webView = UIWebView()
}

//MARK : - 扩展 XMOauthViewController 实现 UIWebViewDelegate 协议
extension XMOauthViewController: UIWebViewDelegate {
    
    /// 开始加载请求
    func webViewDidStartLoad(webView: UIWebView) {
        //显示正在加载
        //showWithStatus 不主动关闭，会一直显示
        SVProgressHUD.showWithStatus("正在玩命加载..", maskType: SVProgressHUDMaskType.Black)
    }
    
    // 加载请求完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭
        SVProgressHUD.dismiss()
    }
    
    /// 询问是否加载 request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL!.absoluteString
        print("urlString:\(urlString)")
        
        //加载的不是回调地址
        if !urlString.hasPrefix(XMNetworkTools.sharedInstance.redirect_uri) {
            return true //可以加载
        }

        
        if let query = request.URL?.query{
            print("query:\(query)")
            let codeString = "code="
            
            if query.hasPrefix(codeString){
            // 确定
            // 转成NSString
            let nsQuery = query as NSString
            
            // 截取code的值
            let code = nsQuery.substringFromIndex(codeString.characters.count)
            print("code:\(code)")
                
            // 获取access token
            loadAccessToken(code)
            }
            else{
                //取消
            }
        }
        
        
        return false
    }
    
    /**
    *  调用网络工具类去加载access token
    
    */
    func loadAccessToken(code: String) {
        XMNetworkTools.sharedInstance.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {

                self.netError("网络不给力.....")
                return
            }
            
            print("result:\(result)")
            let account = XMUserAccount(dict: result!)
            
            //保存到沙盒
            account.saveAccount()
            
            //加载用户数据
            account.loadUserInfo({ (error) -> () in
                if error != nil {
                    self.netError("加载用户数据出错")
                    return
                }
                print("account:\(XMUserAccount.loadAccount())")
                self.close()
            })
        }
        
    }
    private func netError(message : String) {
        SVProgressHUD.showErrorWithStatus(message, maskType: SVProgressHUDMaskType.Black)
        
        // 延迟关闭. dispatch_after 没有提示,可以拖oc的dispatch_after来修改
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            self.close()
            
        })
    }
}